import asyncio
import logging
from typing import Dict, Callable, Any
from fastapi import  WebSocket

from Model.default import get_db
from Model.user.User import user_expand
from api.mysocketio.double_stream import send_double_message
from api.mysocketio.group_stream import send_group_message


#仅仅处理通信,和临时会话。其他均采用api处理,减少压力和用户体验
# 房间管理类（完全依赖数据库）,房间的创建通过api处理,房间只是一个标记位
# 实际是socket连接管理器，为了减少消耗,采用socket来发消息。

class PersistentRoomManager:
    # 实际上他只用作限制,在线,部分进行管理。
    def __init__(self):
        self.lock = asyncio.Lock()  # 用于操作的锁
        self.active_connections:dict={}


    def set_handler(self,handler):
        self.Handler=handler

    async def connect(self, connection: WebSocket):
        # 对于连接后的信息获取更新,采用api形式来处理
        await connection.accept()
        self.active_connections[connection.user_id]=connection

    # 心跳检测

    async def check_connection(self, websocket: WebSocket) -> bool:
        """检查连接是否仍然有效"""
        try:
            if websocket not in self.active_connections:
                return False

            # 使用 Ping 帧检测连接状态
            await websocket.send_text("ping")  # 发送心跳包
            return True
        except Exception as e:
            logging.error(f"心跳检测失败: {e}")
            self.disconnect(websocket)
            return False

    def disconnect(self, websocket: WebSocket):
        """确认无法重连,安全断开连接"""
        try:
            if self.active_connections.get(websocket.user_id):
                # 清除断开连接
                db=get_db()
                db.query(user_expand).filter_by(id=websocket.user_id).socket=None
                db.commit()
                db.close()
                del self.active_connections[websocket.user_id]
                logging.info(f"连接断开，剩余连接数: {len(self.active_connections)}")
                # 执行你的断开处理逻辑
                if websocket:
                    try:
                        #执行断开连接的其他逻辑
                        pass
                    except Exception as e:
                        logging.error(f"处理断开时间失败: {e}")
        except Exception as e:
            logging.error(f"断开连接时出错: {e}")
        finally:
            logging.info("断开连接逻辑结束")


class WebSocketHandler:
    def __init__(self):
        self.room_manager = None
        self.handlers: Dict[str, Callable] = {}

    def register(self, message_type: str):
        def decorator(func: Callable):
            self.handlers[message_type] = func
            return func
        return decorator

    async def handle(self, websocket: WebSocket, data: Dict[str, Any]):
        message_type = data.get("type")
        if handler := self.handlers.get(message_type):
            return await handler(websocket, data)
        await websocket.send_json({
            "type": "error",
            "message": f"Unsupported message type: {message_type}"
        })

    def set_room_manager(self,manager):
            self.room_manager = manager


Handler = WebSocketHandler()
# 执行注册
SEND_MESSAGE_MAPPER={
    'group':send_group_message,
    'double':send_double_message
}
@Handler.register("send_message")
async def send_message(ws:WebSocket,data):
    try:
         message_type=data["room_type"]
         #每次不再传输进入hanlder,只用api借助logindata的socket，但是呢还直接传输所有在线的列表给用于double处理
         #使用api附带操作直接判断是否在线,不再用次socke管理器的状态来进行处理
         await SEND_MESSAGE_MAPPER.get(message_type)(ws,data,MyPersistentRoomManager.active_connections)
    except Exception as e:
        print(e)
        pass


MyPersistentRoomManager = PersistentRoomManager()
MyPersistentRoomManager.set_handler(Handler)

